package com.jeesite.util;

import com.jeesite.model.exception.SFException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author gzm
 * @desc 异常工具类
 * @date 2019/5/24 10:24
 */
public class ExceptionUtil {

  /**
   * description: 抛出业务异常
   *
   * @param clazz 异常类
   * @param exceptionMsg 异常信息
   * @return void
   */
  public static void throwCmsException(Class<? extends SFException> clazz, String exceptionMsg) {
    throwCmsException(true, clazz, exceptionMsg);
  }

  /**
   * description: 抛出业务异常
   *
   * @param autoThrow 是否自动抛出
   * @param clazz 异常类
   * @return void
   */
  public static void throwCmsException(boolean autoThrow, Class<? extends SFException> clazz) {
    throwCmsException(autoThrow, clazz, null);
  }

  /**
   * description: 抛出业务异常
   *
   * @param autoThrow 是否自动抛出
   * @param clazz 异常类
   * @param exceptionMsg 异常信息
   * @return void
   */
  public static void throwCmsException(boolean autoThrow, Class<? extends SFException> clazz,
      String exceptionMsg) {
    if (autoThrow) {
      Constructor<?> constructor;
      SFException cmsException = null;
      try {
        constructor = clazz.getDeclaredConstructor(String.class);
        cmsException = (SFException) constructor.newInstance(exceptionMsg);
      }
      catch (NoSuchMethodException e) {
        e.printStackTrace();
      }
      catch (IllegalAccessException e) {
        e.printStackTrace();
      }
      catch (InstantiationException e) {
        e.printStackTrace();
      }
      catch (InvocationTargetException e) {
        e.printStackTrace();
      }
      if (null != cmsException) {
        throw cmsException;
      }
    }
  }

}
